package com.kuang.annotation;

import javax.print.PrintService;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

//通过反射来创建一个对象,
public class Test09 {
    public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchMethodException, InvocationTargetException, NoSuchFieldException {
        //获得Class对象
        Class c1 = Class.forName("com.kuang.annotation.Person");
        //构造一个对象,通过反射构造对象
//        Person user = (Person) c1.newInstance();//本质上调用无参构造器
//        System.out.println(user);
        //调用有参构造器，然后创建对象
//        Constructor constructor = c1.getDeclaredConstructor(String.class, int.class, int.class);
//        Person user1 = (Person) constructor.newInstance("张三", 12, 15);
//        user1.setName("梨花");
//        user1.setAge(96);
//        user1.setId(18);
//        System.out.println(user1);
       //**********************************************************
        //通过反射调用方法
        //先反射创建对象
        Person user3 = (Person) c1.newInstance();
        //通过反射获取一个方法
        Method setName = c1.getDeclaredMethod("setName", String.class);
        //调用对象的invoke方法
        //invoke进行激活方法，(对象，"方法的值")
        setName.invoke(user3, "陈涛");
        System.out.println(user3.getName());

        Method setAge = c1.getDeclaredMethod("setAge", int.class);
        setAge.invoke(user3,12);
        System.out.println(user3.getAge());

        Method setId = c1.getDeclaredMethod("setId", int.class);
        setId.invoke(user3,7878);
        System.out.println(user3.getId());
        System.out.println(user3.toString());
        System.out.println("========================================");
        //通过反射来创造属性
        Person user4 = (Person) c1.newInstance();
        Field name = c1.getDeclaredField("name");
        //操作属性,对于private修饰的属性，是没有办法访问的
        //可以关闭权限检测，来进行访问
        //取消安全检测
        name.setAccessible(true);//原本的是false
        name.set(user4,"吊袜带");
        System.out.println(user4.getName());


    }
}
